package com.chinanet.auth;

import com.chinanet.oracle.entry.User;
import com.chinanet.oracle.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Arrays;

@Service
public class JwtUserDetailsService implements UserDetailsService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String account) throws UsernameNotFoundException {
        System.out.println("loadUserByUsername");
        User user = userRepository.findByAccount(account);
        if (user == null) {
            throw new UsernameNotFoundException(String.format("No user found with account '%s'.", account));
        } else {
            return new JwtUser(user.getAccount(), user.getPsw(), Arrays.<SimpleGrantedAuthority>asList(new SimpleGrantedAuthority(user.getRole().getRoleName())));
        }
    }

}